/*
 * @Author: fangquan
 * @Date: 2020-6-19 10:00:00
 * @Last Modified by: fangquan
 * @Last Modified time: 2020-6-19 10:00:00 
 * @Usage 常用方法集合
 */

/**
 * @method formatParams 将一段查询字符串格式化为JSON对象
 * @param {String} [search = location.search] 查询参数
 * @returns { Object} JSON对象
 */

export let formatParams = (search = location.search) => {
  let params = new Object();

  if (!search) return params;

  let str = search.includes("?") ? search.substr(1) : search;
  
  let strs = str.split("&");

  strs.map(item => params[item.split("=")[0]] = item.split("=")[1]);

  return params;
}


/**
 * @method getLocalTime 日期
 * @param {String} 时间字符串
 * @returns {String} 格式化后的时间字符串
 */

export let getLocalTime = (nS) => {
  return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
}

/**
 * @method valiIdCard 检验身份证号
 * @param { String } [orginnumber] 身份证号
 * @returns { Boolean } 布尔值
 */
 
export let valiIdCard = (orginnumber) => {
  let partn = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/; //先用正则判断是否为正确的格式
  if (!partn.exec(orginnumber)) {
    return false;
  } else {
    orginnumber = orginnumber.toLowerCase();
    let number = [...orginnumber];
    let ration = new Array("7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", "9", "10", "5", "8", "4", "2"); //系数
    let ration22 = new Array("1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2");
    let sum = 0;
    for (let i = 0; i < number.length - 1; i++) {
      sum = number[i] * ration[i] + sum;
    }
    let mod = sum % 11;
    if (ration22[mod] == number[17]) {
      return true;
    } else {
      return false;
    }
  }
}

/**
 * @method formatTime 格式化时间戳 格式 "yyyy.mm.dd hh:mm:ss S"
 * @remark: 连接符可自定义
 */

export let formatTime = (timeStamp, fmt = "yyyy.mm.dd hh:mm") => {
  let date = new Date(timeStamp);
  let o = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), // 日
    "h+": date.getHours(), // 小时
    "m+": date.getMinutes(), // 分
    "s+": date.getSeconds(), // 秒
    "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
    "S": date.getMilliseconds() // 毫秒
  };
  
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  }

  for (let k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  
  return fmt;
}